const express = require('express')
const app = express()
const path = require('path')
const server = require('http').createServer(app)
const io = require('socket.io')(server)

app.use(express.static(path.join(__dirname, 'public')))

// 所有在线用户
let connectedUsers = []

io.on('connection', socket => {
  updateUsers()
  let user = ''

  // 监听登录
  socket.on('login', (username, callback) => {
    if (username.trim().length === 0) {
      callback(false)
      return
    }
    user = username
    connectedUsers.push(user)
    console.log(connectedUsers)
    updateUsers()
    callback(true)
  })

  //退出
  socket.on('logout', () => {
    if (user === '') {
      return
    }
    connectedUsers.splice(connectedUsers.indexOf(user), 1)
    console.log(connectedUsers)
    updateUsers()
  })

  // 该用户断开连接
  socket.on('disconnect', () => {
    // 剔除该用户
    connectedUsers.splice(connectedUsers.indexOf(user), 1)
    console.log(connectedUsers)
    updateUsers()
  })

  // 通知客户端 更新在线用户列表
  function updateUsers() {
    io.emit('loadUsers', connectedUsers)
  }

  // 接收消息
  socket.on('sendMessage', msg => {
    if (msg === '') {
      return
    }
    io.emit('output', {
      user,
      msg
    })
  })
})


const port = process.env.PROT || 3000

server.listen(port, () => {
  console.log(`server is running on http://localhost:${port}!`)
})